/*
 *                  BioJava development code
 *
 * This code may be freely distributed and modified under the
 * terms of the GNU Lesser General Public Licence.  This should
 * be distributed with the code.  If you do not have a copy,
 * see:
 *
 *      http://www.gnu.org/copyleft/lesser.html
 *
 * Copyright for this code is held jointly by the individual
 * authors.  These should be listed in @author doc comments.
 *
 * For more information on the BioJava project and its aims,
 * or to join the biojava-l mailing list, visit the home page
 * at:
 *
 *      http://www.biojava.org/
 * 
 * Created on Aug 1, 2007
 * 
 */

package dasregistry;

import java.io.IOException;

import javax.servlet.*;
import javax.servlet.http.*;

public class ServletFilter implements Filter {

	String host;
	int port;
	String path;
	
	public void init(FilterConfig config) throws ServletException {
		// TODO Auto-generated method stub
		String h = config.getInitParameter("servlet-host");
        String po = config.getInitParameter("servlet-port");
        
        
        if (h == null) {
            throw new ServletException("Must specify servlet-host");
        }
        if (po == null) {
            throw new ServletException("Must specify servlet-port");
        }
        host = h;
        try {
            port = Integer.parseInt(po);
        } catch (NumberFormatException ex) {
            throw new ServletException("Invalid servlet-port " + po);
        }
        
        String pa = config.getInitParameter("servlet-path");
        path = pa;
        
	}
	
	
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	public void doFilter(ServletRequest request, 
			ServletResponse response, 
			FilterChain chain) throws IOException, ServletException {
			System.out.println("ServletFilter: doFilter");
		  if (request instanceof HttpServletRequest) {
	            request = new HttpServletRequestWrapper((HttpServletRequest) request) {
	                public String getServerName() {
	                    return host;
	                }
	                
	                public int getServerPort() {
	                    return port;
	                }

					public String getPathInfo() {
						System.out.println(" ServletFilter: the parent pathInfo is: " + super.getPathInfo());
						if ( path == null )
							return super.getPathInfo();
						else 
							return path;
					}

					public String getRequestURI() {
						System.out.println(" ServletFilter: getRequestURI " + super.getRequestURI());
						return super.getRequestURI();
					}

					public StringBuffer getRequestURL() {
						System.out.println(" ServletFilter: getRequestURL " + super.getRequestURL());
						return super.getRequestURL();
					}
					
					
	                
	               
	                
	            } ;
	        }
	        chain.doFilter(request, response);
		
		
		
	}

	
	
	

}
